// cloudfunctions/getChatUsers/index.js
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const { stdId } = event;
  try {
    // 查询当前用户发送/接收的所有消息
    const messagesRes = await db.collection('messages')
      .where({ $or: [{ fromUser: stdId }, { toUser: stdId }] })
      .get();
    
    // 提取对方的stdId（去重）
    const chatUsers = [...new Set(
      messagesRes.data.map(msg => msg.fromUser === stdId ? msg.toUser : msg.fromUser)
    )];
    
    return { chatUsers };
  } catch (err) {
    console.error('获取聊天用户失败：', err);
    return { chatUsers: [], errMsg: err.message };
  }
};